package middleware

import (
	"fmt"
	"github.com/cuiyuanxin/airuisi-admin/pkg/config"
	"github.com/gin-gonic/gin"
	"github.com/unrolled/secure"
	"github.com/zztroot/color"
	"go.uber.org/zap"
	"log"
)

func TlsMiddleware(configSetting *config.Configs, loger *zap.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		ssDevelopment := false
		if configSetting.Server.Mode == "debug" {
			ssDevelopment = true
		}
		// 初始化 secure 中间件，开启防止 XSS 和 CSRF 攻击的选项
		secureMiddleware := secure.New(secure.Options{
			SSLRedirect: true,                           // If SSLRedirect is set to true, then only allow HTTPS requests. Default is false.
			SSLHost:     configSetting.Server.SslDomain, // SSLHost is the host name that is used to redirect HTTP requests to HTTPS. Default is "", which indicates to use the same host.
			//STSSeconds:  315360000,                      // STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
			//FrameDeny: true, // If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
			//ContentSecurityPolicy: "default-src 'self'", // ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "". Passing a template string will replace `$NONCE` with a dynamic nonce value of 16 bytes for each request which can be later retrieved using the Nonce function.
			IsDevelopment: ssDevelopment, // This will cause the AllowedHosts, SSLRedirect, and STSSeconds/STSIncludeSubdomains options to be ignored during development.  When deploying to production, be sure to set this to false.
		})
		err := secureMiddleware.Process(c.Writer, c.Request)
		if err != nil {
			if configSetting.Server.Mode == "debug" {
				log.Printf("secureMiddleware.Process err: %s", color.Coat(err.Error(), color.Red))
			} else {
				loger.Error(fmt.Sprintf("secureMiddleware.Process err: %v", err))
			}

			return
		}
		c.Next()
	}
}
